﻿// ----------------------------------------------------------------------------------
// <copyright file="WebContextManager.cs" company="Christopher Hines">
// Copyright (c) 2012 All Right Reserved
// </copyright>
// <author>Chris Hines</author>
// <date>2012-02-15</date>
// <summary>
//     Web-based stateful context manager
// </summary>
// ----------------------------------------------------------------------------------

namespace Copperfield.Sdk
{
    using System;
    using System.Globalization;
    using System.Web;

    /// <summary>
    /// Web-based stateful context manager
    /// </summary>
    /// <typeparam name="T">The context type</typeparam>
    public class WebContextManager<T> : ContextManagerBase<T> where T : IComparable, new()
    {
        /// <summary>
        /// Gets the context key
        /// </summary>
        /// <value>
        /// The context key
        /// </value>
        private readonly string contextKey = string.Concat("ContextFor", typeof(T).Name).GetHashCode().ToString(CultureInfo.InvariantCulture);

        /// <summary>
        /// Gets the current context.
        /// </summary>
        /// <returns>
        /// The current context.
        /// </returns>
        public override T GetContext()
        {
            if (HttpContext.Current.Session == null)
            {
                return new T();
            }

            var context = HttpContext.Current.Session[this.contextKey];

            if (!(context is T))
            {
                return new T();
            }

            return ReferenceEquals((T)context, default(T))
                       ? new T()
                       : (T)context;
        }
        
        /// <summary>
        /// Sets the current context.
        /// </summary>
        /// <param name="context">
        /// The current context.
        /// </param>
        public override void SetContext(T context)
        {
            if (HttpContext.Current.Session == null)
            {
                return;
            }

            HttpContext.Current.Session[this.contextKey] = context;
        }
    }
}
